package org.cloud.jiangyougateway.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 设置过滤器 （TODO 暂不配置认证和权限功能）
 */
// order表示多个过滤器的时候顺序加载  越小优先级越高
//@Component
//@Order(-1)
public class AuthorizeFilter implements GlobalFilter {

    /**
     * 1.获取参数
     * 2.获取参数中的authorize
     * 3.判断参数中是否为admin
     * 4.判断是否进行拦截
     * @param exchange 上下文
     * @param chain 拦截器链
     * @return 拦截结果
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        MultiValueMap<String, String> params = request.getQueryParams();

        String auth = params.getFirst("authorization");
        if ("admin".equals(auth)) {
            // 放行
            return  chain.filter(exchange);
        }
        exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
        // 拦截请求
        return exchange.getResponse().setComplete();
    }
}
